<template>
    <div class="leave-manage">
        <el-tabs v-model="activeTab" @tab-click="onTabClick">
            <el-tab-pane label="今日考勤" name="today" />
            <el-tab-pane label="缺勤统计" name="absence" />
            <el-tab-pane label="历史考勤" name="history" />
            <el-tab-pane label="请假管理" name="leave" />
            <el-tab-pane label="离校管理" name="leaveSchool" />
            <el-tab-pane label="考勤时间设置" name="setting" />
        </el-tabs>
        <div class="filter-bar">
            <el-date-picker v-model="dateRange" type="daterange" range-separator="-" start-placeholder="开始日期"
                end-placeholder="结束日期" style="width: 260px; margin-right: 10px;" />
            <el-select v-model="leaveType" placeholder="请假类型" style="width: 130px; margin-right: 10px;">
                <el-option label="全部" value="" />
                <el-option label="病假" value="病假" />
                <el-option label="事假" value="事假" />
            </el-select>
            <el-select v-model="className" placeholder="班级" style="width: 150px; margin-right: 10px;">
                <el-option v-for="item in classOptions" :key="item" :label="item" :value="item" />
            </el-select>
            <el-select v-model="status" placeholder="状态" style="width: 130px; margin-right: 10px;">
                <el-option label="全部" value="" />
                <el-option label="待审批" value="待审批" />
                <el-option label="已批准" value="已批准" />
                <el-option label="已拒绝" value="已拒绝" />
            </el-select>
            <el-input v-model="studentName" placeholder="学生姓名" style="width: 130px; margin-right: 10px;" />
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="handleReset" style="margin-left: 8px;">重置</el-button>
            <el-button type="success" @click="showAddLeaveDialog" style="margin-left: 8px;">添加请假</el-button>
            <el-button type="info" @click="handleRefresh" style="margin-left: 8px;">
                <el-icon>
                    <Refresh />
                </el-icon> 刷新数据
            </el-button>
        </div>
        <div class="result-info">查询结果：共计 {{ tableData.length }} 条数据</div>
        <el-table :data="tableData" border style="width: 100%; margin-top: 10px;" v-loading="loading">
            <el-table-column prop="startDate" label="开始日期" width="120" />
            <el-table-column prop="endDate" label="结束日期" width="120" />
            <el-table-column prop="className" label="班级" width="140" />
            <el-table-column prop="studentName" label="学生姓名" width="100" />
            <el-table-column prop="leaveType" label="请假类型" width="80" />
            <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                    <el-tag
                        :type="scope.row.status === '已批准' ? 'success' : scope.row.status === '待审批' ? 'warning' : 'danger'">
                        {{ scope.row.status }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="approver" label="审批人" width="100" />
            <el-table-column label="操作" width="240">
                <template #default="scope">
                    <el-button type="primary" size="small" @click="viewLeaveDetail(scope.row)">详情</el-button>
                    <el-button v-if="scope.row.status === '待审批'" type="success" size="small"
                        @click="handleApprove(scope.row)">批准</el-button>
                    <el-button v-if="scope.row.status === '待审批'" type="danger" size="small"
                        @click="handleReject(scope.row)">拒绝</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页控件 -->
        <div class="pagination-container">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 30]"
                layout="total, sizes, prev, pager, next, jumper" :total="totalLeaves" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>

        <!-- 查看请假详情对话框 -->
        <el-dialog v-model="detailDialogVisible" title="请假详情" width="30%">
            <div>
                <p><strong>学生：</strong>{{ currentLeave.studentName }}</p>
                <p><strong>学号：</strong>{{ currentLeave.studentId }}</p>
                <p><strong>班级：</strong>{{ currentLeave.className }}</p>
                <p><strong>请假类型：</strong>{{ currentLeave.leaveType }}</p>
                <p><strong>开始日期：</strong>{{ currentLeave.startDate }}</p>
                <p><strong>结束日期：</strong>{{ currentLeave.endDate }}</p>
                <p><strong>状态：</strong>{{ currentLeave.status }}</p>
                <p v-if="currentLeave.approver"><strong>审批人：</strong>{{ currentLeave.approver }}</p>
                <p><strong>请假原因：</strong></p>
                <div class="reason-content">{{ currentLeave.reason }}</div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="detailDialogVisible = false">关闭</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 添加请假对话框 -->
        <el-dialog v-model="addLeaveDialogVisible" title="添加请假申请" width="40%">
            <el-form :model="leaveForm" label-width="100px" :rules="rules" ref="leaveFormRef">
                <el-form-item label="学生姓名" prop="studentName">
                    <el-input v-model="leaveForm.studentName" placeholder="请输入学生姓名" />
                </el-form-item>
                <el-form-item label="学号" prop="studentId">
                    <el-input v-model="leaveForm.studentId" placeholder="请输入学号" />
                </el-form-item>
                <el-form-item label="班级" prop="className">
                    <el-select v-model="leaveForm.className" placeholder="请选择班级" style="width: 100%;">
                        <el-option v-for="item in classOptions" :key="item" :label="item" :value="item" />
                    </el-select>
                </el-form-item>
                <el-form-item label="请假类型" prop="leaveType">
                    <el-select v-model="leaveForm.leaveType" placeholder="请选择请假类型" style="width: 100%;">
                        <el-option label="病假" value="病假" />
                        <el-option label="事假" value="事假" />
                    </el-select>
                </el-form-item>
                <el-form-item label="请假日期" prop="dateRange">
                    <el-date-picker v-model="leaveForm.dateRange" type="daterange" range-separator="-"
                        start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%;" />
                </el-form-item>
                <el-form-item label="请假原因" prop="reason">
                    <el-input v-model="leaveForm.reason" type="textarea" rows="4" placeholder="请输入请假原因" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addLeaveDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitLeaveForm" :loading="submitting">提交</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, reactive, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, type FormInstance } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { getClassList, getLeaveList, approveLeave, resetCache, addLeaveRecord } from '../../api/kaoqin'
import type { ClassItem, LeaveItem } from '../../api/kaoqin.d.ts'

const router = useRouter()
const route = useRoute()
const activeTab = ref('leave')
const loading = ref(false)
const submitting = ref(false)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const totalLeaves = ref(0)
const allLeaves = ref<LeaveItem[]>([])

// 监听路由变化高亮对应tab
watch(
    () => route.path,
    (path) => {
        if (path.includes('/main/attendance/manage')) {
            activeTab.value = 'today'
        } else if (path.includes('/main/attendance/absence')) {
            activeTab.value = 'absence'
        } else if (path.includes('/main/attendance/history')) {
            activeTab.value = 'history'
        } else if (path.includes('/main/attendance/leave')) {
            activeTab.value = 'leave'
        } else if (path.includes('/main/attendance/leaveSchool')) {
            activeTab.value = 'leaveSchool'
        } else if (path.includes('/main/attendance/setting')) {
            activeTab.value = 'setting'
        }
    },
    { immediate: true }
)

// 标签页切换
function onTabClick(tab: any) {
    if (tab.paneName === 'today') {
        router.push('/main/attendance/manage')
    } else if (tab.paneName === 'absence') {
        router.push('/main/attendance/absence')
    } else if (tab.paneName === 'history') {
        router.push('/main/attendance/history')
    } else if (tab.paneName === 'leave') {
        router.push('/main/attendance/leave')
    } else if (tab.paneName === 'leaveSchool') {
        router.push('/main/attendance/leaveSchool')
    } else if (tab.paneName === 'setting') {
        router.push('/main/attendance/setting')
    }
}

const dateRange = ref(['2025-03-01', '2025-03-31'])
const leaveType = ref('')
const className = ref('')
const studentName = ref('')
const status = ref('')
const classOptions = ref<string[]>([])
const tableData = ref<LeaveItem[]>([])

const detailDialogVisible = ref(false)
const currentLeave = ref<LeaveItem>({} as LeaveItem)

const addLeaveDialogVisible = ref(false)
const leaveFormRef = ref<FormInstance>()
const leaveForm = reactive({
    studentName: '',
    studentId: '',
    className: '',
    leaveType: '',
    dateRange: [] as string[],
    reason: ''
})

const rules = {
    studentName: [{ required: true, message: '请输入学生姓名', trigger: 'blur' }],
    studentId: [{ required: true, message: '请输入学号', trigger: 'blur' }],
    className: [{ required: true, message: '请选择班级', trigger: 'change' }],
    leaveType: [{ required: true, message: '请选择请假类型', trigger: 'change' }],
    dateRange: [{ required: true, message: '请选择请假日期', trigger: 'change' }],
    reason: [{ required: true, message: '请输入请假原因', trigger: 'blur' }]
}

// 获取班级列表
async function fetchClassList() {
    try {
        const response = await getClassList()
        if (response.data && response.data.code === 200) {
            classOptions.value = response.data.data.map((item: ClassItem) => item.className)
        } else {
            classOptions.value = ['一年级（1）班', '一年级（2）班']
        }
    } catch (error) {
        console.error('获取班级列表失败:', error)
        classOptions.value = ['一年级（1）班', '一年级（2）班']
    }
}

// 获取请假列表
async function fetchLeaveList() {
    loading.value = true
    try {
        const params = {
            startDate: dateRange.value ? dateRange.value[0] : '',
            endDate: dateRange.value ? dateRange.value[1] : '',
            leaveType: leaveType.value,
            className: className.value,
            status: status.value,
            studentName: studentName.value
        }

        const response = await getLeaveList(params)
        if (response.data && response.data.code === 200) {
            // 保存所有请假数据用于分页
            allLeaves.value = response.data.data
            totalLeaves.value = allLeaves.value.length
            updatePagedData()
        } else {
            ElMessage.error('获取请假列表失败')
        }
    } catch (error) {
        console.error('获取请假列表失败:', error)
        ElMessage.error('获取请假列表失败')
    } finally {
        loading.value = false
    }
}

// 更新分页数据
function updatePagedData() {
    const startIndex = (currentPage.value - 1) * pageSize.value
    const endIndex = startIndex + pageSize.value
    tableData.value = allLeaves.value.slice(startIndex, endIndex)
}

// 处理分页大小变化
function handleSizeChange(size: number) {
    pageSize.value = size
    updatePagedData()
}

// 处理当前页变化
function handleCurrentChange(page: number) {
    currentPage.value = page
    updatePagedData()
}

// 查询按钮
function handleQuery() {
    currentPage.value = 1
    fetchLeaveList()
}

// 重置按钮
function handleReset() {
    dateRange.value = ['2025-03-01', '2025-03-31']
    leaveType.value = ''
    className.value = ''
    studentName.value = ''
    status.value = ''
    currentPage.value = 1
    fetchLeaveList()
}

// 刷新数据按钮 - 重置缓存并获取新的动态数据
async function handleRefresh() {
    loading.value = true
    try {
        // 重置API缓存，生成新的随机数据
        resetCache()

        ElMessage({
            message: '正在刷新数据...',
            type: 'info'
        })

        // 重新获取班级和请假数据
        await fetchClassList()
        await fetchLeaveList()

        ElMessage({
            message: '数据刷新成功！',
            type: 'success'
        })
    } catch (error) {
        console.error('刷新数据失败:', error)
        ElMessage.error('刷新数据失败')
    } finally {
        loading.value = false
    }
}

// 查看请假详情
function viewLeaveDetail(row: LeaveItem) {
    currentLeave.value = row
    detailDialogVisible.value = true
}

// 显示添加请假对话框
function showAddLeaveDialog() {
    addLeaveDialogVisible.value = true
    Object.assign(leaveForm, {
        studentName: '',
        studentId: '',
        className: classOptions.value[0] || '',
        leaveType: '病假',
        dateRange: [],
        reason: ''
    })
}

// 提交请假表单
async function submitLeaveForm() {
    if (!leaveFormRef.value) return

    await leaveFormRef.value.validate(async (valid) => {
        if (valid) {
            submitting.value = true
            try {
                // 处理日期范围
                const startDate = leaveForm.dateRange[0] ? formatDate(leaveForm.dateRange[0]) : '';
                const endDate = leaveForm.dateRange[1] ? formatDate(leaveForm.dateRange[1]) : '';

                // 创建新的请假记录
                const leaveData = {
                    studentName: leaveForm.studentName,
                    studentId: leaveForm.studentId,
                    className: leaveForm.className,
                    leaveType: leaveForm.leaveType,
                    startDate,
                    endDate,
                    reason: leaveForm.reason,
                    status: '待审批',
                    approver: ''
                };

                // 调用API添加请假记录
                const response = await addLeaveRecord(leaveData);

                if (response.data && response.data.code === 200) {
                    ElMessage.success('请假申请提交成功');
                    addLeaveDialogVisible.value = false;
                    currentPage.value = 1; // 回到第一页以查看新添加的记录
                    fetchLeaveList(); // 刷新列表
                } else {
                    ElMessage.error(response.data?.message || '提交失败');
                }
            } catch (error) {
                console.error('提交请假申请失败:', error);
                ElMessage.error('提交请假申请失败');
            } finally {
                submitting.value = false;
            }
        }
    })
}

// 日期格式化工具函数
function formatDate(date: any) {
    if (!date) return '';

    if (typeof date === 'string') {
        return date;
    }

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');

    return `${year}-${month}-${day}`;
}

// 批准请假
async function handleApprove(row: LeaveItem) {
    try {
        const data = {
            status: '已批准',
            approver: '王老师' // 实际项目中应该从登录用户中获取
        }

        const response = await approveLeave(row.id, data)

        if (response.data && response.data.code === 200) {
            ElMessage.success('已批准该请假申请')
            fetchLeaveList() // 刷新列表
        } else {
            ElMessage.error('操作失败')
        }
    } catch (error) {
        console.error('批准请假失败:', error)
        ElMessage.error('批准请假失败')
    }
}

// 拒绝请假
async function handleReject(row: LeaveItem) {
    try {
        const data = {
            status: '已拒绝',
            approver: '王老师' // 实际项目中应该从登录用户中获取
        }

        const response = await approveLeave(row.id, data)

        if (response.data && response.data.code === 200) {
            ElMessage.success('已拒绝该请假申请')
            fetchLeaveList() // 刷新列表
        } else {
            ElMessage.error('操作失败')
        }
    } catch (error) {
        console.error('拒绝请假失败:', error)
        ElMessage.error('拒绝请假失败')
    }
}

// 组件挂载时获取数据
onMounted(() => {
    // 确保请假管理页面的标签页正确显示
    if (route.path.includes('/main/attendance/leave')) {
        activeTab.value = 'leave'
    }
    fetchClassList()
    fetchLeaveList()
})
</script>

<style scoped>
.leave-manage {
    background: #f7fafd;
    padding: 20px;
}

.filter-bar {
    margin: 20px 0 10px 0;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
}

.result-info {
    margin-bottom: 10px;
    color: #409eff;
}

.reason-content {
    background-color: #f5f7fa;
    border-radius: 4px;
    padding: 10px;
    margin-top: 5px;
    min-height: 80px;
}

.pagination-container {
    margin-top: 20px;
    text-align: right;
}
</style>